<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="设备ID" prop="deviceId" label-width="50">
        <el-select
          v-model="queryParams.deviceId"
          filterable
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
          placeholder="请选择设备ID"
        >
          <el-option
            v-for="item in placeManagerOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="ip地址" prop="ipAddress">
        <el-input
          v-model="queryParams.ipAddress"
          placeholder="请输入ip地址"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="更新时间" >
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '23:59:59']"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="small"
          @click="handleQuery"
        >搜索
        </el-button
        >
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery"
        >重置
        </el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          @click="goBack"
          v-show="$route.query.deviceId"
          size="mini"
          icon="el-icon-back"
          type="success"
          plain
        >
          返回
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['monitor:status:export']"
        >导出
        </el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="logList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        label="设备ID"
        align="center"
        prop="deviceId"
        width="190"
      />
      <el-table-column
        label="设备名称"
        align="center"
        prop="deviceName"
        width="190"
      />
      <el-table-column label="内存使用率" align="center" prop="memoryRate" width="100">
        <template slot-scope="scope">
          <el-tag size="small" effect="dark" :type="isTagType(scope.row.memoryRate)">
            {{ scope.row.memoryRate ? scope.row.memoryRate + '%' : "-" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="CPU使用率" align="center" prop="cpuRate" width="100">
        <template slot-scope="scope">
          <el-tag size="small" effect="dark" :type="isTagType(scope.row.cpuRate)">
            {{ scope.row.cpuRate ? scope.row.cpuRate + '%' : "-" }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="磁盘使用率" align="center" prop="diskRate" width="100">
        <template slot-scope="scope">
          <el-tag size="small" effect="dark" :type="isTagType(scope.row.diskRate)">
            {{ scope.row.diskRate ? scope.row.diskRate + '%' : "-" }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="纸张剩余量" align="center" prop="paperRate" width="100">
        <template slot-scope="scope">
          <el-tag size="small" effect="dark" :type="isTagType(scope.row.paperRate,false)">
            {{ scope.row.paperRate ? scope.row.paperRate + '%' : "-" }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="青色墨盒剩余量" align="center" prop="ccolor" width="120">
        <template slot-scope="scope">
          <el-tag size="small" effect="dark" :type="isTagType(scope.row.ccolor,false)">
            {{ scope.row.ccolor ? scope.row.ccolor + '%' : "-" }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="品红色墨盒剩余量" align="center" prop="mcolor" width="140">
        <template slot-scope="scope">
          <el-tag size="small" effect="dark" :type="isTagType(scope.row.mcolor,false)">
            {{ scope.row.mcolor ? scope.row.mcolor + '%' : "-" }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="黄色墨盒剩余量" align="center" prop="ycolor" width="120">
        <template slot-scope="scope">
          <el-tag size="small" effect="dark" :type="isTagType(scope.row.ycolor,false)">
            {{ scope.row.ycolor ? scope.row.ycolor + '%' : "-" }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column label="黑色墨盒剩余量" align="center" prop="kcolor" width="120">
        <template slot-scope="scope">
          <el-tag size="small" effect="dark" :type="isTagType(scope.row.kcolor,false)">
            {{ scope.row.kcolor ? scope.row.kcolor + '%' : "-" }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        label="更新时间"
        align="center"
        prop="updateTime"
        width="180"
      />

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row, scope.index)"
            v-hasPermi="['monitor:status:query']"
          >详细
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['monitor:status:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!--设备状态日志详细对话框-->
    <el-dialog
      title="状态日志详细"
      :visible.sync="equipmentStatusLogOpen"
      width="900px"
      append-to-body
    >
      <u-descriptions-list :column-config="descriptions">
        <template
          v-for="item in descriptionsSlotList"
          :slot="item.slot"
        >
          <el-tag size="small" effect="dark" :type="isTagType(item.value,item.higherIsDanger || false)">
            {{ item.value|| "-" }}
          </el-tag>
        </template>
      </u-descriptions-list>
      <div slot="footer" class="dialog-footer">
        <el-button @click="equipmentStatusLogOpen = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listStatusLog,
  getStatusLog,
  delStatusLog,
  addStatusLog,
  updateStatusLog,
} from "@/api/monitor/equipmentStatus";
import UDescriptionsList from '@/components/UDescriptionsList'

export default {
  name: "DeviceStatusLog",
  components: {UDescriptionsList},
  dicts: ['warnValue'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备状态日志表格数据
      logList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deviceId: null,
        ipAddress: null,
        startTime: null,
        endTime: null,
        status: 0,
      },
      // 表单参数
      form: {},
      //时间
      dateRange: [],
      // 表单校验
      rules: {
        updateTime: [
          {required: true, message: "更新时间不能为空", trigger: "blur"},
        ],
      },
      //控制详情按钮
      equipmentStatusLogOpen: false,
      descriptions: [
        {label: '操作系统', key: 'osVersion', span: '1', value: ''},
        {label: '中间件版本', key: 'middlewareVersion', span: '1', value: ''},
        {label: '本机IP地址', key: 'ipAddress', span: '1', value: ''},
        {label: '本机MAC地址', key: 'mac', span: '1', value: ''},
        {label: 'CPU', key: 'cpu', span: '1', value: ''},
        {label: 'CPU使用率', key: 'cpuRate', span: '1', value: '', slot: 'cpuRate', higherIsDanger: true},
        {label: '内存', key: 'memory', span: '1', value: ''},
        {label: '内存使用率', key: 'memoryRate', span: '1', value: '', slot: 'memoryRate', higherIsDanger: true},
        {label: '硬盘', key: 'disk', span: '1', value: ''},
        {label: '硬盘使用率', key: 'diskRate', span: '1', value: '', slot: 'diskRate', higherIsDanger: true},
        {label: 'C（青色）', key: 'ccolor', span: '1', value: '', slot: 'ccolor'},
        {label: 'M（品红色）', key: 'mcolor', span: '1', value: '', slot: 'mcolor'},
        {label: 'Y（黄色）', key: 'ycolor', span: '1', value: '', slot: 'ycolor'},
        {label: 'K（黑色）', key: 'kcolor', span: '1', value: '', slot: 'kcolor'},
        {label: '纸张剩余量百分比', key: 'paperRate', span: '2', value: '', slot: 'paperRate'},
        {label: '其他检测到的状态信息', key: 'otherMessage', span: '2', value: ''},
        {label: '数据更新时间', key: 'updateTime', span: '2', value: ''},
      ],
      // 告警阈值
      warningRange:{
        heightIsDanger: 70,
        warning: 50,
        lowIsDanger: 30,
      }
    };
  },
  computed: {
    //获取添加修改设备ID下拉框数据
    placeManagerOptions() {
      return this.$store.state.device.placeManagerOptions || []
    },
    descriptionsSlotList(){
      return this.descriptions.filter(item => item.slot)
    }
  },
  methods: {
    /** 查询设备状态日志列表 */
    getList() {
      this.loading = true;
      if (this.dateRange != null) {
        this.queryParams.startTime = this.dateRange[0];
        this.queryParams.endTime = this.dateRange[1];
      } else {
        this.queryParams.startTime = null;
        this.queryParams.endTime = null;
      }
      listStatusLog(this.queryParams).then((response) => {
        // 是否已经加载过设备列表标记改为true
        if (!this.alreadyGetList) this.alreadyGetList = true;
        this.logList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 详细按钮操作 */
    handleView(row) {
      this.equipmentStatusLogOpen = true;
      this.descriptions.map(item => {
        item.value = row[item.key]
        return item
      })
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.dateRange = [];
      this.form = {
        id: null,
        deviceId: null,
        osVersion: null,
        memoryRate: null,
        cpuRate: null,
        diskRate: null,
        ipAddress: null,
        mac: null,
        status: 0,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.deviceId = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加设备状态日志";
    },
    /** 返回设备部署页面 */
    goBack() {
      this.$router.go(-1);
    },
    isTagType(num, higherIsDanger = true) {
      if (num === null) return '';
      let percentNum = parseInt(num);
      if (higherIsDanger) { //数值高为红色警告 小于30为success 30 - 70为wraning 大于70为danger
        return percentNum <= this.warningRange.lowIsDanger ? 'success' : percentNum < this.warningRange.heightIsDanger ? 'warning' : percentNum >= this.warningRange.heightIsDanger ? 'danger' : '';
      } else { //数值低为红色警告  小于30为danger 30 - 70为wraning  大于70为success
        return percentNum <= this.warningRange.lowIsDanger ? 'danger' : percentNum < this.warningRange.heightIsDanger ? 'warning' : percentNum >= this.warningRange.heightIsDanger ? 'success' : '';
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getStatusLog(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备状态日志";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateStatusLog(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStatusLog(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      this.$modal
        .confirm('是否确认删除该设备心跳日志？')
        .then(function () {
          return delStatusLog(ids);
        })
        .then(() => {
          this.$modal.msgSuccess("删除成功");
          this.getList();
        })
        .catch(() => {
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const currentDate = this.parseTime(new Date());
      const ids = this.ids;
      this.download(
        "/deployment/system/export",
        {
          ...this.queryParams
        },
        `设备状态日志_${currentDate}.xlsx`,
        ids,
      );
    },
  },
  watch:{
    'dict.type.warnValue':{
      handler(value){
        value.forEach(item =>{
          if(item.value){
            this.warningRange[item.label] = Number(item.value)
          }
        })
      }
    }
  },
  beforeRouteEnter(to, from, next) {
    const {deviceId} = to.query;
    // 如果存在跳转参数deviceInnerCode,自动填入查询条件
    if (deviceId) {
      next(vm => {
        vm.resetForm("queryForm");
        vm.queryParams.deviceId = deviceId;
        vm.getList();
      })
    } else {
      // 不存在查询参数，
      next(vm => {
        // 是否已加载过列表，第一次进入才调用获取列表接口
        if (!vm.alreadyGetList) {
          vm.getList();
        }
      });
    }
  },
  // 在离开页面时清空跳转携带的参数 暂时不用
  /*  beforeRouteLeave(to, from, next) {
      // 如果当前路由存在deviceInnerCode参数，跳转前清空参数
      if (this.$route.query.deviceId) {
        this.queryParams.deviceId = null;
        // 重新加载列表
        this.getList();
      }
      next();
    },*/
};
</script>
<style lang="scss">

</style>
